package com.shire.shire_interface.controller.timeline;

import com.alibaba.fastjson.JSONObject;
import com.shire.shire_interface.common.bin.Response;
import com.shire.shire_interface.constants.WxConstants;
import com.shire.shire_interface.controller.BaseController;
import com.shire.shire_interface.model.command.WxCommand;
import com.shire.shire_interface.model.timeline.WxFriendTimeline;
import com.shire.shire_interface.model.timeline.WxFriendTimelineExample;
import com.shire.shire_interface.model.user.WxAccount;
import com.shire.shire_interface.service.account.WxAccountService;
import com.shire.shire_interface.service.commandcenter.BaseCommandProcessor;
import com.shire.shire_interface.service.commandcenter.WxCommandService;
import com.shire.shire_interface.service.timeline.WxFriendTimelineService;
import com.shire.shire_interface.service.timeline.WxTimelineFileService;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

//@Api(tags = "查看朋友圈")
@RestController
@RequestMapping("/timeline")
public class WxFriendTimelineController extends BaseController {
    @Resource
    private WxFriendTimelineService wxFriendTimelineService;
    @Resource
    private WxTimelineFileService wxTimelineFileService;
    @Resource
    private WxAccountService accountService;

    @Resource
    private WxCommandService commandService;

    @Resource
    private BaseCommandProcessor commandProcessor;

//    @ApiOperation(value = "取好友朋友圈，post body传入属性csId, wxAccount, friendWxid（为空时取当前wxAccount的全部朋友圈）, pageSize pageNo")
//    @ApiResponses({@ApiResponse(code = 200, message = "调用成功返回", response = Response.class)})
    @PostMapping("/getFriendTimelines")
    public Response getFriendTimelines(@RequestBody JSONObject jsonObject, HttpSession session){
        Response response = new Response();
        Integer csId = jsonObject.getInteger("csId");
        String wxAccount = jsonObject.getString("wxAccount");
        String friendWxid = jsonObject.getString("friendWxid");
        Integer pageSize = jsonObject.getInteger("pageSize");
        Integer pageNo = jsonObject.getInteger("pageNo");

        try {
            if (!checkLoginUserByCsId(session, csId)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }

            WxFriendTimelineExample friendTimelineExample = new WxFriendTimelineExample();
            WxFriendTimelineExample.Criteria criteria = friendTimelineExample.createCriteria().andWxaccountEqualTo(wxAccount);
            friendTimelineExample.setLimitStart(getPageStartRow(pageNo,pageSize));
            friendTimelineExample.setLimitSize(pageSize);
            friendTimelineExample.setOrderByClause("timelineid desc");
            if (StringUtils.isNotBlank(friendWxid)){
                criteria.andFriendwxidEqualTo(friendWxid);
            }
            response.success("成功");
            response.setData(wxFriendTimelineService.selectByExample(friendTimelineExample));

        }catch (Exception e){
            e.printStackTrace();
            response.error("发生错误：" + e.getMessage());
        }
        return response;
    }

//    @ApiOperation(value = "根据Tid好友朋友圈，post body传入属性csId, wxAccount, tid")
//    @ApiResponses({@ApiResponse(code = 200, message = "调用成功返回", response = Response.class)})
    @PostMapping("/getTimelineByTid")
    public Response getTimelineByTid(@RequestBody JSONObject jsonObject, HttpSession session){
        Response response = new Response();
        Integer csId = jsonObject.getInteger("csId");
        String wxAccount = jsonObject.getString("wxAccount");
        String tid = jsonObject.getString("tid");

        try {
            if (!checkLoginUserByCsId(session, csId)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }

            WxFriendTimeline friendTimeline = wxFriendTimelineService.selectByTid(wxAccount, tid);
            response.success("成功");
            response.setData(friendTimeline);
        }catch (Exception e){
            e.printStackTrace();
            response.error("发生错误：" + e.getMessage());
        }
        return response;
    }

//    @ApiOperation(value = "取好友朋友圈，post body传入属性csId, wxAccount, friendWxid（为空时取当前wxAccount的全部朋友圈)")
//    @ApiResponses({@ApiResponse(code = 200, message = "调用成功返回", response = Response.class)})
    @PostMapping("/refreshFriendTimeline")
    public Response refreshFriendTimeline(@RequestBody JSONObject jsonObject, HttpSession session){
        Response response = new Response();
        Integer csId = jsonObject.getInteger("csId");
        String wxAccount = jsonObject.getString("wxAccount");
        String friendWxid = jsonObject.getString("friendWxid");

        try {
            if (!checkLoginUserByCsId(session, csId)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }
            WxAccount account = accountService.getWxAccountByWxId(wxAccount);
            WxCommand command;
            if (wxAccount.equals(friendWxid))
                command = commandService.generateCmdObject(getCurrentUser(session).getId(),account.getId(),"{}",WxConstants.CmdTaskType.UNKNOWN,-1, WxConstants.CmdType.CRK_FETCH_TIMELINE_D,WxConstants.CmdPriority.UNKNOWN);
            else {
                JSONObject reqJson = new JSONObject();
                reqJson.put("wxId",friendWxid);
                reqJson.put("lastTid", -1);
                command = commandService.generateCmdObject(getCurrentUser(session).getId(),account.getId(),reqJson.toJSONString(),WxConstants.CmdTaskType.UNKNOWN,-1, WxConstants.CmdType.CRK_FETCH_USERTIMELINE_D,WxConstants.CmdPriority.UNKNOWN);
            }

            commandProcessor.addCommand(getCurrentUser(session).getId(),account.getId(),command);
            response.success("操作成功");
        }catch (Exception e){
            e.printStackTrace();
            response.error("发生错误：" + e.getMessage());
        }
        return response;
    }


//    @ApiOperation(value = "取好友朋友圈文件，post body是文件mid，以逗号分隔")
//    @ApiResponses({@ApiResponse(code = 200, message = "调用成功返回", response = Response.class)})
    @PostMapping("/getTimelineFileUrls")
    public Response getTimelineFileUrls(@RequestBody String body, HttpSession session){
        Response response = new Response();
        if (StringUtils.isBlank(body)){
            response.error("参数错误");
            return response;
        }
        try {
            if (!checkLoginUser(session)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }
            JSONObject midObject = JSONObject.parseObject(body);
            String mids = midObject.getString("mid");
            if (StringUtils.isNotBlank(mids)) {
                List<String> midList = Arrays.asList(mids);
                response.success("操作成功");
                response.setData(wxTimelineFileService.getFilesByIdList(midList));
            }else {
                response.success("操作成功");
            }

        }catch (Exception e){
            e.printStackTrace();
            response.error("发生错误：" + e.getMessage());
        }
        return response;
    }

//    @ApiOperation(value = "点赞或取消友朋友圈，post body传入属性csId, wxAccount, friendWxid（为空时取当前wxAccount的全部朋友圈)，tid")
//    @ApiResponses({@ApiResponse(code = 200, message = "调用成功返回", response = Response.class)})
    @PostMapping("/sendLike")
    public Response sendLike(@RequestBody JSONObject jsonObject, HttpSession session){
        Response response = new Response();
        Integer csId = jsonObject.getInteger("csId");
        String wxAccount = jsonObject.getString("wxAccount");
        String friendWxid = jsonObject.getString("friendWxid");
        String tid = jsonObject.getString("tid");

        try {
            if (!checkLoginUserByCsId(session, csId)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }

            WxFriendTimeline timeline = wxFriendTimelineService.selectByTid(wxAccount,tid);
            WxConstants.CmdType cmdType;
            if (timeline.getLiked() !=null && timeline.getLiked() == 1){
                cmdType = WxConstants.CmdType.CRK_UNLIKE_TIMELINE_D;
                timeline.setLiked(0);
            }else {
                cmdType = WxConstants.CmdType.CRK_LIKE_TIMELINE_D;
                timeline.setLiked(1);
            }
            WxAccount account = accountService.getWxAccountByWxId(wxAccount);
            JSONObject commentJson = new JSONObject();
            commentJson.put("tid",tid);
            commentJson.put("toWxId",friendWxid);
            WxCommand command = commandService.generateCmdObject(getCurrentUser(session).getId(),account.getId(),commentJson.toJSONString(),WxConstants.CmdTaskType.UNKNOWN,-1, cmdType,WxConstants.CmdPriority.UNKNOWN);
            commandProcessor.addCommand(getCurrentUser(session).getId(),account.getId(),command);
            wxFriendTimelineService.updateFriendTimeline(timeline);
            //更新数据
            command = commandService.generateCmdObject(getCurrentUser(session).getId(),account.getId(),"{}",WxConstants.CmdTaskType.UNKNOWN,-1, WxConstants.CmdType.CRK_FETCH_TIMELINE_D,WxConstants.CmdPriority.UNKNOWN);
            commandProcessor.addCommand(getCurrentUser(session).getId(),account.getId(),command);response.success("操作成功");
        }catch (Exception e){
            e.printStackTrace();
            response.error("发生错误：" + e.getMessage());
        }
        return response;
    }

//    @ApiOperation(value = "评论朋友圈，post body传入属性csId, wxAccount, friendWxid（为空时取当前wxAccount的全部朋友圈)，tid, comment")
//    @ApiResponses({@ApiResponse(code = 200, message = "调用成功返回", response = Response.class)})
    @PostMapping("/commentFriendLine")
    public Response commentFriendLine(@RequestBody JSONObject jsonObject, HttpSession session){
        Response response = new Response();
        Integer csId = jsonObject.getInteger("csId");
        String wxAccount = jsonObject.getString("wxAccount");
        String friendWxid = jsonObject.getString("friendWxid");
        String tid = jsonObject.getString("tid");
        String comment = jsonObject.getString("comment");

        try {
            if (!checkLoginUserByCsId(session, csId)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }
            WxAccount account = accountService.getWxAccountByWxId(wxAccount);
            JSONObject commentJson = new JSONObject();
            commentJson.put("tid",tid);
            commentJson.put("toWxId",friendWxid);
            commentJson.put("content", comment);
            WxCommand command = commandService.generateCmdObject(getCurrentUser(session).getId(),account.getId(),commentJson.toJSONString(),WxConstants.CmdTaskType.UNKNOWN,-1, WxConstants.CmdType.CRK_COMMENT_TIMELINE_D,WxConstants.CmdPriority.UNKNOWN);
            commandProcessor.addCommand(getCurrentUser(session).getId(),account.getId(),command);
            //更新数据
            command = commandService.generateCmdObject(getCurrentUser(session).getId(),account.getId(),"{}",WxConstants.CmdTaskType.UNKNOWN,-1, WxConstants.CmdType.CRK_FETCH_TIMELINE_D,WxConstants.CmdPriority.UNKNOWN);
            commandProcessor.addCommand(getCurrentUser(session).getId(),account.getId(),command);response.success("操作成功");
        }catch (Exception e){
            e.printStackTrace();
            response.error("发生错误：" + e.getMessage());
        }
        return response;
    }

//    @ApiOperation(value = "取消评论朋友圈，post body传入属性csId, wxAccount, friendWxid（为空时取当前wxAccount的全部朋友圈)，tid, commentId,comment64Id ")
//    @ApiResponses({@ApiResponse(code = 200, message = "调用成功返回", response = Response.class)})
    @PostMapping("/uncommentFriendLine")
    public Response uncommentFriendLine(@RequestBody JSONObject jsonObject, HttpSession session){
        Response response = new Response();
        Integer csId = jsonObject.getInteger("csId");
        String wxAccount = jsonObject.getString("wxAccount");
        String friendWxid = jsonObject.getString("friendWxid");
        String tid = jsonObject.getString("tid");
        String commentId = jsonObject.getString("commentId");
        String comment64Id = jsonObject.getString("comment64Id");


        try {
            if (!checkLoginUserByCsId(session, csId)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }
            WxAccount account = accountService.getWxAccountByWxId(wxAccount);
            JSONObject commentJson = new JSONObject();
            commentJson.put("tid",tid);
            commentJson.put("toWxId",friendWxid);
            commentJson.put("commentId", commentId);
            commentJson.put("comment64Id", comment64Id);
            WxCommand command = commandService.generateCmdObject(getCurrentUser(session).getId(),account.getId(),commentJson.toJSONString(),WxConstants.CmdTaskType.UNKNOWN,-1, WxConstants.CmdType.CRK_UNCOMMENT_TIMELINE_D,WxConstants.CmdPriority.UNKNOWN);
            commandProcessor.addCommand(getCurrentUser(session).getId(),account.getId(),command);
            //更新数据
            command = commandService.generateCmdObject(getCurrentUser(session).getId(),account.getId(),"{}",WxConstants.CmdTaskType.UNKNOWN,-1, WxConstants.CmdType.CRK_FETCH_TIMELINE_D,WxConstants.CmdPriority.UNKNOWN);
            commandProcessor.addCommand(getCurrentUser(session).getId(),account.getId(),command);response.success("操作成功");
        }catch (Exception e){
            e.printStackTrace();
            response.error("发生错误：" + e.getMessage());
        }
        return response;
    }
}
